package ysq.xyg.recovery.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.recovery.dao.RecoveryCircleOrderDao;
import ysq.xyg.recovery.model.po.RecoveryCircleOrder;
import ysq.xyg.recovery.model.po.RecoveryWasteMember;
import ysq.xyg.recovery.model.vo.RecoveryCircleOrderVo;
import ysq.xyg.recovery.service.PowerMemberService;
import ysq.xyg.recovery.service.RecoveryCircleOrderService;
import ysq.xyg.recovery.service.RecoveryWasteMemberService;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.wxapi.api.WxApiClient;
import ysq.xyg.wxapi.model.base.TemplateMessage;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 回收金模块-回收商圈订单service实现
 *
 * @author congcong tao
 * @date 2019-8-1 15:03:02
 */
@Service("recoveryCircleOrderService")
public class RecoveryCircleOrderServiceImpl extends BaseServiceImpl<RecoveryCircleOrder> implements RecoveryCircleOrderService {

    @Autowired
    private PowerMemberService powerMemberService;
    @Autowired
    private RecoveryWasteMemberService recoveryWasteMemberService;
    @Resource
    private RecoveryCircleOrderDao recoveryCircleOrderDao;
    private RecoveryCircleOrder recoveryCircleOrder;

    @Autowired
    public void setBaseDao(RecoveryCircleOrderDao recoveryCircleOrderDao) {
        this.baseDao = recoveryCircleOrderDao;
    }

    /**
     * 分页查询
     *
     * @param recoveryCircleOrderVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-8-1 15:03:02
     */
    @Override
    public ReturnEntity page(RecoveryCircleOrderVo recoveryCircleOrderVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<RecoveryCircleOrder> list = acceptList(recoveryCircleOrderVo);
        PageInfo<RecoveryCircleOrder> page=new PageInfo<RecoveryCircleOrder>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageLeft(RecoveryCircleOrderVo recoveryCircleOrderVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        if (StringUtil.isNotEmpty(recoveryCircleOrderVo.getMemberNickName())) {
            recoveryCircleOrderVo.setMemberNickName(BaseUtil.encodeBase64String(recoveryCircleOrderVo.getMemberNickName()));
        }
        if (StringUtil.isNotEmpty(recoveryCircleOrderVo.getWasteMemberNickName())) {
            recoveryCircleOrderVo.setWasteMemberNickName(BaseUtil.encodeBase64String(recoveryCircleOrderVo.getWasteMemberNickName()));
        }
        List<RecoveryCircleOrder> list = recoveryCircleOrderDao.selectEntityList(recoveryCircleOrderVo);
        if (list != null && list.size() > 0) {
            for (RecoveryCircleOrder recoveryCircleOrder : list) {
                if (StringUtils.isNotEmpty(recoveryCircleOrder.getMemberNickName())) {
                    recoveryCircleOrder.setMemberNickName(BaseUtil.decodeBase64(recoveryCircleOrder.getMemberNickName()));
                }
                if (StringUtils.isNotEmpty(recoveryCircleOrder.getWasteMemberNickName())) {
                    recoveryCircleOrder.setWasteMemberNickName(BaseUtil.decodeBase64(recoveryCircleOrder.getWasteMemberNickName()));
                }
            }
        }
        PageInfo<RecoveryCircleOrder> page=new PageInfo<RecoveryCircleOrder>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param recoveryCircleOrderVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-8-1 15:03:02
     */
    @Override
    public ReturnEntity addOrUpdate(RecoveryCircleOrderVo recoveryCircleOrderVo, SysUser currentUser) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(recoveryCircleOrderVo.getId())){
            recoveryCircleOrder=new RecoveryCircleOrder(currentUser);
            isUpate=false;
        }else{
            recoveryCircleOrder=selectByPrimaryKey(recoveryCircleOrderVo.getId());
            if(ObjectUtil.isNull(recoveryCircleOrder)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            recoveryCircleOrder.setUpdateTime(new Date());
            recoveryCircleOrder.setUpdateUser(currentUser.getId());
        }
        recoveryCircleOrder.setMemberId(recoveryCircleOrderVo.getMemberId());
        recoveryCircleOrder.setCatCode(recoveryCircleOrderVo.getCatCode());
        recoveryCircleOrder.setCompanyName(recoveryCircleOrderVo.getCompanyName());
        recoveryCircleOrder.setPhone(recoveryCircleOrderVo.getPhone());
        recoveryCircleOrder.setAddress(recoveryCircleOrderVo.getAddress());
        recoveryCircleOrder.setContent(recoveryCircleOrderVo.getContent());
        recoveryCircleOrder.setImage(recoveryCircleOrderVo.getImage());
        recoveryCircleOrder.setType(recoveryCircleOrderVo.getType());
        recoveryCircleOrder.setPrice(recoveryCircleOrderVo.getPrice());
        recoveryCircleOrder.setStatus(recoveryCircleOrderVo.getStatus());
        recoveryCircleOrder.setManageContent(recoveryCircleOrderVo.getManageContent());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(recoveryCircleOrder);
        }else{
            num=insert(recoveryCircleOrder);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }

    @Override
    public ReturnEntity addOrUpdate(RecoveryCircleOrderVo recoveryCircleOrderVo) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(recoveryCircleOrderVo.getId())){
            recoveryCircleOrder = new RecoveryCircleOrder();
            recoveryCircleOrder.setId(BaseUtil.uId());
            recoveryCircleOrder.setCreateTime(DateUtil.date());
            recoveryCircleOrder.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
            recoveryCircleOrder.setUpdateTime(DateUtil.date());
            isUpate=false;
        }else{
            recoveryCircleOrder = selectByPrimaryKey(recoveryCircleOrderVo.getId());
            if(ObjectUtil.isNull(recoveryCircleOrder)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            recoveryCircleOrder.setUpdateTime(new Date());
        }
        recoveryCircleOrder.setName(recoveryCircleOrderVo.getName());
        recoveryCircleOrder.setMemberId(recoveryCircleOrderVo.getMemberId());
        recoveryCircleOrder.setCatCode(recoveryCircleOrderVo.getCatCode());
        recoveryCircleOrder.setCompanyName(recoveryCircleOrderVo.getCompanyName());
        recoveryCircleOrder.setPhone(recoveryCircleOrderVo.getPhone());
        recoveryCircleOrder.setAddress(recoveryCircleOrderVo.getAddress());
        recoveryCircleOrder.setContent(recoveryCircleOrderVo.getContent());
        recoveryCircleOrder.setImage(recoveryCircleOrderVo.getImage());
        recoveryCircleOrder.setType(recoveryCircleOrderVo.getType());
        recoveryCircleOrder.setPrice(recoveryCircleOrderVo.getPrice());
        recoveryCircleOrder.setStatus(recoveryCircleOrderVo.getStatus());
        recoveryCircleOrder.setManageContent(recoveryCircleOrderVo.getManageContent());
        // reserveTime
        if (StringUtils.isNotEmpty(recoveryCircleOrderVo.getReserveTime())) {
            recoveryCircleOrder.setReserveTime(DateUtil.parse(recoveryCircleOrderVo.getReserveTime(), DatePattern.NORM_DATETIME_MINUTE_PATTERN));
        }
        int num = 0;
        if (isUpate) {
            num = updateByPrimaryKey(recoveryCircleOrder);
        } else {
            num = insert(recoveryCircleOrder);
        }
        if (num <= 0) {
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        // 发出预约申请
        TemplateMessage templateMessage=new TemplateMessage();
        templateMessage.setUrl("");
        // 找到管理端预约人
        String openId = powerMemberService.selectOpenIdByType(BaseConstant.POWER_MEMBER_ORDER);
        templateMessage.setOpenid(openId);
        templateMessage.setTemplateId("RjlsC46UYLHJbaA1LhARw43sCIHLjIMinZg2z4ZjvsA");
        Map<String,String> data=new HashMap<String, String>();
        data.put("first", "您有一个用户预约");
        data.put("keyword1", recoveryCircleOrder.getName());
        data.put("keyword2", recoveryCircleOrder.getPhone());
        data.put("keyword3", recoveryCircleOrderVo.getReserveTime());
        data.put("keyword4", recoveryCircleOrder.getContent());
        data.put("remark", "备注：请尽快查处理");
        templateMessage.setDataMap(data);
        WxApiClient.sendTempletNotice(templateMessage);
        return new ReturnEntity();
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-8-1 15:03:02
     */
    @Override
    public ReturnEntity delete(String id, SysUser currentUser) {
        RecoveryCircleOrder recoveryCircleOrder=selectByPrimaryKey(id);
        if(recoveryCircleOrder!=null){
            recoveryCircleOrder.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            recoveryCircleOrder.setUpdateTime(new Date());
            recoveryCircleOrder.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(recoveryCircleOrder);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param recoveryCircleOrderVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong tao
     * @date 2019-8-1 15:03:02
     */
    @Override
    public List<RecoveryCircleOrder> acceptList(RecoveryCircleOrderVo recoveryCircleOrderVo){
        Example example = new Example(RecoveryCircleOrder.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(recoveryCircleOrderVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",recoveryCircleOrderVo.getRemoveTag());
        }
        example.setOrderByClause(" update_time desc");
        return recoveryCircleOrderDao.selectByExample(example);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateWasteMemberId(String ids, String wasteMemberId, String manageContent) {
        if (StringUtils.isEmpty(ids)) {
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            RecoveryCircleOrder recoveryCircleOrder = new RecoveryCircleOrder();
            recoveryCircleOrder.setId(id);
            recoveryCircleOrder.setWasteId(wasteMemberId);
            RecoveryWasteMember recoveryWasteMember = recoveryWasteMemberService.selectByPrimaryKey(wasteMemberId);
            recoveryCircleOrder.setWasteMemberId(recoveryWasteMember.getMemberId());
            recoveryCircleOrder.setManageContent(manageContent);
            int info = this.updateByPrimaryKeySelective(recoveryCircleOrder);
            if (info <= 0) {
                return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
            }
        }
        return new ReturnEntity();
    }
}
